package com.yf.dialup;

import java.util.ArrayList;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlSerializer;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.util.Xml;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {
	private EditText et_number;

	// 当activity创建的时候就会调用onCreate方法
	// 通常在onCreate方法中做初始化操作
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// 加载布局文件，并渲染页面
		setContentView(R.layout.activity_main);
		// 1. 找到要操作的控件对应的java对象，findViewById返回值是View, View是android控件的基类
		et_number = (EditText) findViewById(R.id.editText1);
		Button btn_call = (Button) findViewById(R.id.button1);
		Button btn_call2 = (Button) findViewById(R.id.button2);
		Button btn_call3 = (Button) findViewById(R.id.button3);

		// 2. 给按钮添加点击事件（第一种写法：内部类）
		btn_call.setOnClickListener(new MyOnClickListener());

		// 给按钮添加点击事件（第二种写法：匿名内部类）
		btn_call2.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				MainActivity.this.ringUp();
			}

		});

		// 给按钮添加点击事件（第三种写法：Activity实现OnClickListener接口）
		btn_call3.setOnClickListener(this);
	}

	private class MyOnClickListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			MainActivity.this.ringUp();
		}

	}

	private void ringUp() {
		// 3. 获取用户输入
		String number = et_number.getText().toString().trim();
		// 4. 判断用户输入是否为空
		if (TextUtils.isEmpty(number)) {
			// 5. 提示用户输入不能为空，不要忘记要调用show方法才能把Toast显示出来
			Toast.makeText(MainActivity.this, "电话号码不能为空", Toast.LENGTH_SHORT).show();
		} else {
			// Intent是对要进行的操作的抽象描述
			Intent intent = new Intent();
			// 给意图设置动作，即要执行的操作
			intent.setAction(Intent.ACTION_CALL);
			// 统一资源标示符，不同于Url它可以自定义协议，Url只是Uri的子集
			// "tel:"表示协议，系统能自动识别
			Uri data = Uri.parse("tel:" + number);
			// 给意图设置要携带的数据
			intent.setData(data);
			// 6. 打开拨号器
			startActivity(intent);

		}
	}

	@Override
	public void onClick(View v) {
		// 点击页面上所有setOnClickListener(this)的控件都会调用此方法
		System.out.println(Integer.toHexString(v.getId()));
		if (v.getId() == R.id.button3) {
			this.ringUp();
		}
	}

	// 给按钮添加点击事件（第三种写法：在activity_main.xml中控件上声明android:onClick="事件处理方法名"）
	public void handleButton4Click(View v) {
		System.out.println(Integer.toHexString(v.getId()));
		this.ringUp();
	}

	public void handleSaveFile(View v) {
		System.out.println(Integer.toHexString(v.getId()));
		FileUtil.saveUserByContextWithWorld(MainActivity.this, "MODE_WORLD_READABLE");
		Toast.makeText(MainActivity.this, "已保存用户信息到应用私有目录", Toast.LENGTH_SHORT).show();
	}

	public void handleReadFile(View v) {
		try {
			String msg = FileUtil.loadMsgByPath("data/data/com.yf.dialup/files/msg.txt");
			Log.v("handleReadFile", msg.toString());
			Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
		} catch (Exception e) {
			// TODO
			e.printStackTrace();
			Toast.makeText(MainActivity.this, "读取失败", Toast.LENGTH_SHORT).show();
		}
	}

	public void saveSms2xml(View v) {
		try {
			ArrayList<SMS> list = new ArrayList<SMS>();

			for (int i = 0; i < 5; i++) {
				SMS sms = new SMS("10086" + i, "content" + i, "2021-6-16 11:30" + i);
				list.add(sms);
			}

			XmlSerializer xmlSerializer = Xml.newSerializer();
			xmlSerializer.setOutput(openFileOutput("smslist.xml", MODE_PRIVATE), "utf-8");

			xmlSerializer.startDocument("utf-8", true);
			xmlSerializer.startTag(null, "smslist");

			for (SMS sms : list) {
				xmlSerializer.startTag(null, "sms");

				xmlSerializer.startTag(null, "from");
				xmlSerializer.text(sms.getFrom());
				xmlSerializer.endTag(null, "from");

				xmlSerializer.startTag(null, "content");
				xmlSerializer.text(sms.getContent());
				xmlSerializer.endTag(null, "content");

				xmlSerializer.startTag(null, "time");
				xmlSerializer.text(sms.getTime());
				xmlSerializer.endTag(null, "time");

				xmlSerializer.endTag(null, "sms");
			}

			xmlSerializer.endTag(null, "smslist");
			xmlSerializer.endDocument();
			Toast.makeText(MainActivity.this, "保存短信成功", Toast.LENGTH_SHORT).show();
		} catch (Exception e) {
			e.printStackTrace();
			Toast.makeText(MainActivity.this, "保存短信失败", Toast.LENGTH_SHORT).show();
		}
	}

	public void loadSmsFromxml(View v) {
		try {
			XmlPullParser parser = Xml.newPullParser();
			parser.setInput(openFileInput("smslist.xml"), "utf-8");
			int eventType = parser.getEventType();
			
			ArrayList<SMS> list = new ArrayList<SMS>();;
			SMS sms = null;
			
			while (eventType != XmlPullParser.END_DOCUMENT) {
				switch (eventType) {
				case XmlPullParser.START_TAG:
					if ("smslist".equals(parser.getName())) {
						list = new ArrayList<SMS>();
					} else if ("sms".equals(parser.getName())) {
						sms = new SMS();
					} else if ("from".equals(parser.getName()) && sms != null) {
						sms.setFrom(parser.nextText());
					} else if ("content".equals(parser.getName()) && sms != null) {
						sms.setContent(parser.nextText());
					} else if ("time".equals(parser.getName()) && sms != null) {
						sms.setTime(parser.nextText());
					}
					break;
				case XmlPullParser.END_TAG:
					if ("sms".equals(parser.getName()) && sms != null) {
						list.add(sms);
						sms = null;
					}

					break;
				default:
					break;
				}
				
				eventType = parser.next();
			}

			Log.v("xml", list.toString());
			Toast.makeText(MainActivity.this, "读取短信条数：" + list.size(), Toast.LENGTH_SHORT).show();
		} catch (Exception e) {
			e.printStackTrace();
			Toast.makeText(MainActivity.this, "读取短信失败", Toast.LENGTH_SHORT).show();
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

}
